<template>
  <div class="forum">
    <div class="container">

      <div class="page-header">
        <div>
          <h1>宠物交流论坛</h1>
        </div>
        <div class="header-actions" v-if="isLoggedIn">
          <el-button type="primary" @click="goToCreatePost" icon="el-icon-edit">发布新帖</el-button>
        </div>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-filter-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input v-model="searchKeyword" placeholder="搜索帖子标题" prefix-icon="el-icon-search" clearable>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="selectedCategory" placeholder="选择分类" clearable style="width: 100%;">
              <el-option label="全部分类" value=""></el-option>
              <el-option label="养护经验" value="养护经验"></el-option>
              <el-option label="领养心得" value="领养心得"></el-option>
              <el-option label="健康咨询" value="健康咨询"></el-option>
              <el-option label="训练技巧" value="训练技巧"></el-option>
              <el-option label="其他交流" value="其他交流"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="filterPosts">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-section">
        <el-card v-if="loading" class="loading-card">
          <div class="loading-content">
            <i class="el-icon-loading"></i>
            <span>加载中...</span>
          </div>
        </el-card>

        <div v-else-if="posts.length === 0" class="empty-state">
          <div class="empty-icon">📋</div>
          <p>暂无帖子</p>
          <el-button type="primary" @click="goToCreatePost" v-if="isLoggedIn">发布第一个帖子</el-button>
        </div>

        <div v-else class="posts-list">
          <el-card v-for="post in posts" :key="post.id" class="post-card" @click.native="goToPostDetail(post.id)">
            <div class="post-header">
              <div class="post-category">
                <el-tag :type="getCategoryType(post.category)" size="small">
                  {{ post.category }}
                </el-tag>
              </div>
              <div class="post-actions">
                <el-button type="text" :class="{ 'favorited': post.isCollection }" @click.stop="toggleFavorite(post)"
                  icon="el-icon-star-off">
                  {{ post.collection || 0 }}
                </el-button>
              </div>
            </div>

            <h3 class="post-title">{{ post.title }}</h3>
            <p class="post-summary" v-html="post.summary"></p>

            <div class="post-meta">
              <div class="author-info">
                <el-avatar :size="24" :src="post.avatar">
                  {{ post.name.charAt(0) }}
                </el-avatar>
                <span class="author-name">{{ post.name }}</span>
              </div>
              <div class="post-stats">
                <span class="stat-item">
                  <i class="el-icon-view"></i>
                  {{ post.views || 0 }}
                </span>
                <span class="stat-item">
                  <i class="el-icon-chat-dot-round"></i>
                  {{ post.comments || 0 }}
                </span>
                <span class="post-time">{{ formatTime(post.createTime) }}</span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-wrapper">
          <el-pagination @current-change="handlePageChange" @size-change="handleSizeChange" :current-page="currentPage"
            :page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :total="total"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRescueList } from '@/api/forum'
import { addForumCollection, cancelCollection } from '@/api/forum-collection'
import { mapGetters } from 'vuex'
export default {
  name: 'Forum',
  data() {
    return {
      loading: true,
      searchKeyword: '',
      selectedCategory: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchTimer: null,
      posts: []
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn', 'user']),
  },
  methods: {
    async loadPosts() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }

        // 添加分类筛选
        if (this.selectedCategory) {
          params.category = this.selectedCategory
        }

        // 添加标题搜索
        if (this.searchKeyword.trim()) {
          params.title = this.searchKeyword.trim()
        }

        const response = await getRescueList(params)

        if (response.code === 200) {
          this.posts = response.data.rows || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.message || '获取帖子列表失败')
        }
      } catch (error) {
        this.$message.error('加载帖子失败')
        console.error('加载帖子失败:', error)
      } finally {
        this.loading = false
      }
    },

    filterPosts() {
      this.currentPage = 1
      this.loadPosts()
    },

    resetFilter() {
      this.searchKeyword = ''
      this.selectedCategory = ''
      this.filterPosts()
    },

    handlePageChange(page) {
      this.currentPage = page
      this.loadPosts()
    },

    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadPosts()
    },

    goToCreatePost() {
      this.$router.push('/forum/create')
    },

    goToPostDetail(postId) {
      this.$router.push(`/forum/post/${postId}`)
    },

    async toggleFavorite(post) {
      try {
        if (post.isCollection) {
          const res = await cancelCollection({ forumId: post.id })
          if (res.code === 200) {
            post.isCollection = false
            post.collection = Math.max((post.collection || 0) - 1, 0)
            this.$message.success('已取消收藏')
          } else {
            this.$message.error(res.message || '取消收藏失败')
          }
        } else {
          const res = await addForumCollection({
            forumId: post.id,
            userId: this.user.userId,
            userName: this.user.userName,
            ...post
          })
          if (res.code === 200) {
            post.isCollection = true
            post.collection = (post.collection || 0) + 1
            this.$message.success('已收藏')
          } else {
            this.$message.error(res.message || '收藏失败')
          }
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },

    getCategoryType(category) {
      const typeMap = {
        '养护经验': 'success',
        '领养心得': 'primary',
        '健康咨询': 'warning',
        '训练技巧': 'info',
        '其他交流': ''
      }
      return typeMap[category] || ''
    },

    formatTime(date) {
      if (!date) return ''
      const now = new Date()
      const diff = now - new Date(date)
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return new Date(date).toLocaleDateString()
      }
    }
  },

  mounted() {
    this.loadPosts()
  },

  beforeDestroy() {
    // 清理定时器，防止内存泄漏
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  }
}
</script>

<style scoped>
.forum {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.posts-section {
  margin-top: 20px;
}

.loading-card {
  text-align: center;
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-state i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.post-actions .el-button.favorited {
  color: #f56c6c;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.post-summary {
  color: #7f8c8d;
  line-height: 1.6;
  margin: 0 0 16px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #909399;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-weight: 500;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-item i {
  font-size: 14px;
}

.post-time {
  color: #c0c4cc;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}
</style>